// Package logicConfig -----------------------------
// @file      : cardConfig.go
// @author    : WuZhouHai
// @contact   : wzh200x@126.com
// @time      : 2024/3/5 16:22
// @desc      :
// -------------------------------------------
package config

import (
	"context"
	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/container/gmap"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/util/gconv"
	"phoenix/apps/examples/phoenix_app_dwys/model/gameConfig"
	"phoenix/phoenix/base"
	"phoenix/phoenix/common/logger"
	"phoenix/phoenix/interfaces"
	"phoenix/phoenix/utils"
)

type CardConfig struct {
	base.BaseLogicConfig
}

func NewCardConfig(configName string, configFile string, ctx context.Context) (interfaces.ILogicConfig, error) {
	return &CardConfig{
		BaseLogicConfig: base.NewBaseLogicConfig(configName, configFile, ctx),
	}, nil
}

func (this *CardConfig) InitLogicConfig() {
	fileData, err := this.LoadConfigFile()
	if err != nil {
		logger.PhoenixLoggerIns().Errorf("CardConfig load config %s error: %s", this.GetFileName(), err)
		return
	}
	if j, err := gjson.DecodeToJson(fileData); err != nil {
		logger.PhoenixLoggerIns().Errorf("CardConfig decode config %s error: %s", this.GetFileName(), err)
	} else {
		var configs []gameConfig.ChooseCard
		if err := j.Scan(&configs); err != nil {
			logger.PhoenixLoggerIns().Errorf("CardConfig scan config %s error: %s", this.GetFileName(), err)
		}
		chooseCardAnalysis := new(gameConfig.CardConfigAnalysis)
		for i, config := range configs {
			this.SetConfigItem(config.Id, &configs[i])
			this.AnalysisRangeInfo(&chooseCardAnalysis.FixedCards, &chooseCardAnalysis.RangeCards, config.ChooseNormal)
			this.AnalysisRangeInfo(&chooseCardAnalysis.FixedCardsTotal, &chooseCardAnalysis.RangeCardsTotal, config.ChooseNormalTotal)
			this.SetConfigExtendData(config.Id, chooseCardAnalysis)
		}
	}
}

func (this *CardConfig) AnalysisRangeInfo(fixed *gmap.IntIntMap, rangeArray *garray.Array, configData string) {
	if configData == "" {
		return
	}
	chooseInfos := utils.SplitString(configData, ";")
	for _, chooseInfo := range chooseInfos {
		chooseNormalInfoArray := utils.SplitString(chooseInfo, ",")
		if len(chooseNormalInfoArray) != 2 {
			logger.PhoenixLoggerIns().Errorf("CardConfig chooseNormalInfoArray length error: %s", chooseNormalInfoArray)
			continue
		}
		chooseRangeInfo := utils.SplitString(chooseNormalInfoArray[0], "-")
		chooseMin := gconv.Int32(chooseRangeInfo[0])
		chooseMax := gconv.Int32(chooseRangeInfo[1])
		chooseGroupId := gconv.Int32(chooseNormalInfoArray[1])
		if chooseMin == chooseMax {
			if chooseGroupId > 0 {
				fixed.Set(int(chooseMin), int(chooseGroupId))
			}
		} else {
			chooseRange := new(gameConfig.ChooseRange)
			chooseRange.Min = chooseMin
			chooseRange.Max = chooseMax
			chooseRange.ChooseGroupId = chooseGroupId
			rangeArray.Append(chooseRange)
		}
	}
}
